package com.zhentao.file.service.impl;

import com.zhentao.file.config.MinIoConfig;
import com.zhentao.file.config.MinIoConfigProperties;
import com.zhentao.file.service.FileStorageService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;

/**
 * @Date 2024/2/23 11:53
 * @Author xdm
 **/
@Service
@EnableConfigurationProperties(MinIoConfigProperties.class)
@Import(MinIoConfig.class)
public class FileStorageServiceImpl implements FileStorageService {
    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinIoConfigProperties minIOConfigProperties;

    @Override
    public String uploadImgFile(String prefix, String filename, InputStream inputStream) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {


        filename = prefix + "-" + UUID.randomUUID() + filename;
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(filename)
                .contentType("image/jpg")
                .bucket(minIOConfigProperties.getBucket())
                .stream(inputStream, inputStream.available(), -1)
                .build();

        minioClient.putObject(putObjectArgs);
        System.out.println("上传成功");
        //获取文件的访问路径
       String desPath= minioClient.getObjectUrl(minIOConfigProperties.getBucket(),filename);
        return desPath;
    }

    @Override
    public String uploadHtmlFile(String prefix, String filename, InputStream inputStream) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        filename = prefix + "-" + UUID.randomUUID() + filename;
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(filename)
                .contentType("text/html")
                .bucket(minIOConfigProperties.getBucket())
                .stream(inputStream, inputStream.available(), -1)
                .build();

        minioClient.putObject(putObjectArgs);

        return minIOConfigProperties.getReadPath() +"/"+ minIOConfigProperties.getBucket()+"/" + filename;

    }

    @Override
    public void delete(String pathUrl) {

    }

    @Override
    public byte[] downLoadFile(String pathUrl) {
        return new byte[0];
    }
}
